package com.example.transactiondemo.controller;

import com.example.transactiondemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //编程式事务
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/del")
    public int delByID(Integer id) {
        if (id != null && id > 0) {
            //1.开启事务
            TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
            //2.业务操作
            int result = userService.del(id);
            System.out.println("删除" + result);
            //3.提交事务或者回滚事务
           /* dataSourceTransactionManager.commit(transactionStatus);//提交事务*/
            //回滚事务，不会污染我们的数据库
            dataSourceTransactionManager.rollback(transactionStatus);
            return result;
        }
        return 0;
    }
}
